﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ingebet.Model;
using Ingebet.Model.Enum;

namespace Ingebet.Web
{
    public partial class Resultat : BasePage
    {
        private int? rencID;

        public int RencID
        {
            get
            {
                if (rencID == null)
                {
                    string val = Session["RencontreID"].ToString();
                    int id;
                    if (int.TryParse(val , out id))
                    {
                        rencID = id;
                    }
                }
                return rencID.Value;
            }
        }

        protected void Page_Load(object sender , EventArgs e)
        {
            if (!IsPostBack)
            {
                var ren = Global.Container.Resolve<RencontreModel>().GetByID(RencID);
                this.lblEquipe1.Text = ren.Equipe1.Nom;
                this.lblEquipe2.Text = ren.Equipe2.Nom;
            }
        }

        protected void btnEnregistrer_Click(object sender , EventArgs e)
        {
            int res;

            if (this.radioGain.Checked)
            {
                res = (int)EnumResultat.Gain;
            }
            else if (this.radioEgal.Checked)
            {
                res = (int)EnumResultat.Egalite;
            }
            else
            {
                res = (int)EnumResultat.Perte;
            }
            var rencontre = Global.Container.Resolve<RencontreModel>().GetByID(RencID);
            rencontre.Resultat = res;
            rencontre.Score = this.txtScore.Text;
            Global.Container.Resolve<RencontreModel>().Update(rencontre);
            var lstPari = Global.Container.Resolve<PariModel>().UpdatePariByRencontre(RencID);
            float cote;
            switch (res)
            {
                case 0:
                    cote = rencontre.CoteMatch.CoteGain;
                    break;

                case 1:
                    cote = rencontre.CoteMatch.CoteEgalite;
                    break;

                default:
                    cote = rencontre.CoteMatch.CotePerte;
                    break;
            }
            foreach (var item in lstPari)
            {
                var util = Global.Container.Resolve<UtilisateurModel>().GetByID(item.UtilID);
                if (item.Resultat == res)
                {
                    util.Solde = util.Solde + (item.MontantPari * cote);
                    Global.Container.Resolve<UtilisateurModel>().Update(util);
                }
            }
            this.ClientScript.RegisterStartupScript(this.GetType() , "" , "window.close();" , true);
        }
    }
}